import axios from "axios";


export async function generateImageFX(prompt, count = 4) {
    const APIFY_TOKEN = "apify_api_aMMWcFzSFRhJYbX67H2FNlDhs3ZsmH2aONLm";
    const IMAGEFX_AUTH_TOKEN="ya29.a0AS3H6NymgSIpNi5sErNdyGCQlgaG7VAQfMzsMMgSBC99REI1-DQqwfFnTtO3JtwvGfUmbQa5TraT5B0xtioD6-RumiGtq-CsacOGLy0CDWyk7Qt5A7iSbTDGza7kTjcL4gvQOpNEv3L8dZJpiNZbilG_tBH30RZH4eBPNsrmzBpnZs2ESmQt3DRWG-WH2RxrhZ91XqRQcw0N6mVHAnKb4UY2PvIexbBSzd2YGq6gY80Ypt2c5A5KlLoEyca5GZuBuq3kkaMolw7cEvgXhzp-_uFKQJ3KosvjWVhGPYx0bcVtV1vF42xhVyHh-DqDhkAQCN_0rT4UrIMWaCgYKAeESARMSFQHGX2Mi9dPUNh8DUt0W6kCcghswdQ0339"
    // 1. 启动Actor，count由参数控制
    const startRes = await axios.post(
        `https://api.apify.com/v2/acts/ib4ngz~imagefx-api/runs?token=${APIFY_TOKEN}`,
        {
            authList: [IMAGEFX_AUTH_TOKEN],
            promptList: [prompt],
            count: count,  // 这里改成动态传入
            fileExtension: "jpeg",
            createZip: false
        }
    );

    const runId = startRes.data.data.id;
    console.log("Started run:", runId);

    // 2. 轮询状态
    let status = "";
    let datasetId = "";
    while (true) {
        const statusRes = await axios.get(
            `https://api.apify.com/v2/actor-runs/${runId}?token=${APIFY_TOKEN}`

        );
        status = statusRes.data.data.status;
        console.log("Current status:", status);

        if (status === "SUCCEEDED") {
            datasetId = statusRes.data.data.defaultDatasetId;
            break;
        }
        if (status === "FAILED" || status === "ABORTED" || status === "TIMED-OUT") {
            throw new Error("Image generation failed: " + status);
        }
        await new Promise((resolve) => setTimeout(resolve, 5000));
    }

    // 3. 获取结果
    const datasetRes = await axios.get(
        `https://api.apify.com/v2/datasets/${datasetId}/items?token=${APIFY_TOKEN}`

    );
    return datasetRes.data; // 返回数组 [{prompt, imageName, imageUrl}]
}
